// pages/goods/list/index.js
const { fetchGoodsList, fetchAllWines } = require('../../../services/good/fetchGoodsList');
const { getUserData } = require('../../../model/user');
const config = require('../../../utils/config');

Page({
  data: {
    userInfo: null,
    cabinetGoods: [],
    mallGoods: [],
    isLoading: true,
    scannedCabinetUserId: null,
    isScannedCabinet: false,  // 是否为扫码的酒柜
    activeTab: 'mall',
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
            active: 1
        })
    }
    this.loadUserInfo();
  },

  switchTab(event) {
    const tab = event.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },

  onShareAppMessage() {
    return {
      title: "美酒城市",
      path: "/pages/welcome/welcome",
    }
  },

  async loadUserInfo() {
    try {
      // 处理扫码获取的酒柜信息
      const scannedCabinetUserId = wx.getStorageSync('scannedCabinetUserId');
      const user = getUserData();
  
      if (!user.info.id) {
        reject(new Error('用户未登录或未获取到用户信息'));
        return;
      }
      const { role, id, parentId } = user.info;

      if (scannedCabinetUserId) {
        this.setData({
          scannedCabinetUserId,
          isScannedCabinet: true, // 标识当前展示的是扫码后的酒柜商品
        });

        this.loadGoods(scannedCabinetUserId, true);
      } else {
        this.setData({
          isScannedCabinet: false,
        });
        // 根据用户角色加载商品数据
        switch (role) {
          case 'ADMIN':
          case 'AREA_AGENT':
          case 'GUEST':
            this.loadAllWines();
            break;
          case 'CABINET_OWNER':
            this.loadGoods(id, true); // 加载柜主的商品
            break;
          case 'MEMBER':
            if (parentId) {
              this.loadGoods(parentId, true); // 加载其所从属柜主的商品
            } else {
              console.warn('VIP会员没有绑定柜主，加载所有红酒');
              this.loadAllWines();
            }
            break;
          default:
            console.warn('未知角色，加载所有红酒');
            this.loadAllWines();
            break;
        }
      }

      this.setData({ userInfo: user.info });
    } catch (error) {
      console.error('加载用户信息失败', error);
      wx.showToast({ title: '加载失败' + error, icon: 'error' });
    }
  },

  async loadGoods(userId, isCabinet) {
    try {
        // 柜主配置的酒类放在前面
      const goods = await fetchGoodsList(userId);

      // 过滤掉 isDeleted 为 true 的商品
      let refinedGoods = goods
      .filter(good => !good.isDeleted && good.isPublished)
      .map(good => ({
        ...good,
        imageUrl: `${config.backendUrl}${good.imageUrl.startsWith("/") ? good.imageUrl : "/" + good.imageUrl}`,
      }))
      .sort((a, b) => a.displayOrder - b.displayOrder); // 按 displayOrder 排序

      const allgoods = await fetchAllWines();
      // 过滤柜主配置的酒，放在列表后面
      const otherGoods = allgoods
      .filter(good => 
        !goods.find(g => g.id === good.id) && !good.isDeleted && good.isPublished
      )
      .map(good => ({
        ...good,
        imageUrl: `${config.backendUrl}${good.imageUrl.startsWith("/") ? good.imageUrl : "/" + good.imageUrl}`,
      }))
      .sort((a, b) => a.displayOrder - b.displayOrder);

      refinedGoods = refinedGoods.concat(otherGoods);
      if (isCabinet) {
        this.setData({ activeTab: 'cabinet',cabinetGoods: refinedGoods, isLoading: false });
      } else {
        this.setData({ activeTab: 'mall',mallGoods: allgoods, isLoading: false });
      }
    } catch (error) { 
      console.error('加载商品列表失败', error);
      wx.showToast({ title: '加载失败', icon: 'error' });
    }
  },

  async loadAllWines() {
    try {
      const goods = await fetchAllWines();

      const refinedGoods = goods
      .filter(good => !good.isDeleted && good.isPublished)
      .map(good => ({
        ...good,
        imageUrl: `${config.backendUrl}${good.imageUrl.startsWith("/") ? good.imageUrl : "/" + good.imageUrl}`,
      }))
      .sort((a, b) => a.displayOrder - b.displayOrder);
      
      this.setData({ 
        activeTab: 'mall',
        mallGoods:refinedGoods, 
        isLoading: false });
    } catch (error) {
      console.error('加载红酒列表失败', error);
      wx.showToast({ title: '加载失败', icon: 'error' });
    }
  },

  navigateBack() {
    wx.navigateBack();
  },

  viewDetails(event) {
    const { id } = event.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/goods/details/index?id=${id}`,
    });
  },
});